const db = require('../db/index')
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken') // 生成 token 
const config = require('../config') //导入密钥配置
exports.regUser = (req, res) => {
  const userInfo = req.body
  if (!userInfo.username || !userInfo.password) {
    return res.cc('用户名和密码不能为空')
  }
  const sql = 'select * from ev_users where username =?'
  db.query(sql, userInfo.username, (err, result) => {
    if (err) {
      return res.cc(err)
    }
    if (result.length > 0) {
      return res.cc('用户名已被占用')
    }
    userInfo.password = bcrypt.hashSync(userInfo.password, 10)
    const sql = 'insert into ev_users set ?'
    db.query(sql, {
      username: userInfo.username,
      password: userInfo.password
    }, (err, result) => {
      if (err) {
        return res.cc(err)
      }
      if (result.affectedRows !== 1) {
        return res.cc('注册用户失败，请稍后再试！')
      }
      res.cc('注册成功', 0)
    })
  })
}

exports.login = (req, res) => {
  const userInfo = req.body
  if (!userInfo.username || !userInfo.password) {
    return res.cc('用户名或密码不为空')
  }
  let sql = 'select * from ev_users where username = ?'
  db.query(sql, userInfo.username, (err, result) => {
    if (err) {
      return res.cc(err)
    } else if (result.length === 0) {
      return res.cc('用户不存在')
    }
    const compareResult = bcrypt.compareSync(userInfo.password, result[0].password)
    if (!compareResult) {
      return res.cc('用户名或密码输入错误')
    }
    // 定义生成token的用户信息
    let user = {
      ...result[0],
      password: '',
      user_pic: ''
    }
    // 生成token
    const tokenStr = jwt.sign(user, config.jwtSecretKey, {expiresIn: '10h'})
    // 给客户端发送 token
    res.send({
      status: 0,
      message: '登陆成功',
      token: 'Bearer '+ tokenStr
    })
  })
}